package com.example.wordmemory;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.example.wordmemory.utils.WordDBHelper;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.components.AxisBase;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;

public class LearningProgress extends AppCompatActivity {

    private WordDBHelper dbHelper;
    private TextView tvTodayLearn, tvTodayReview, tvTodayAccuracy, tvTodayShouldReview;
    private LineChart lineChart;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_learning_progress);

        dbHelper = new WordDBHelper(this);

        tvTodayLearn = findViewById(R.id.tv_today_learn);
        tvTodayReview = findViewById(R.id.tv_today_review);
        tvTodayAccuracy = findViewById(R.id.tv_today_accuracy);
//        tvTodayShouldReview = findViewById(R.id.tv_today_should_review);

        lineChart = findViewById(R.id.line_chart);

        // 返回主页按钮
        findViewById(R.id.btn_back_main).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LearningProgress.this, MainActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(intent);
                finish();
            }
        });

        loadTodayStats();
        loadHistoryChart();
    }

    private void loadTodayStats() {
        int learn = dbHelper.getTodayLearnCount();
        int reviewed = dbHelper.getTodayReviewCount();
//        int shouldReview = dbHelper.countTodayNeedReviewWords();
        int correct = 0, total = 0;
        String today = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
        Cursor c2 = dbHelper.getReadableDatabase().rawQuery(
                "SELECT is_memorized FROM study WHERE date(review_time)=?", new String[]{today});
        while (c2.moveToNext()) {
            total++;
            if (c2.getInt(0) == 1) correct++;
        }
        c2.close();
        int accuracy = (total > 0) ? (int) (correct * 100.0 / total) : 0;
        tvTodayLearn.setText("今日学习：" + learn);
        tvTodayReview.setText("今日已复习：" + reviewed);
        tvTodayAccuracy.setText("正确率：" + accuracy + "%");
    }

    private void loadHistoryChart() {
        // 查询最近7天的学习和复习数
        ArrayList<Entry> learnEntries = new ArrayList<>();
        ArrayList<Entry> reviewEntries = new ArrayList<>();
        ArrayList<String> xLabels = new ArrayList<>();

        // 子查询获取最近7条记录，外层查询按日期升序排列，以正确绘制图表
        Cursor c = dbHelper.getReadableDatabase().rawQuery(
                "SELECT date, learn_count, review_count FROM " +
                "(SELECT * FROM calendar ORDER BY date DESC LIMIT 7) " +
                "ORDER BY date ASC", null);
        
        int index = 0;
        while (c.moveToNext()) {
            String date = c.getString(0);
            int learn = c.getInt(1);
            int review = c.getInt(2);
            learnEntries.add(new Entry(index, learn));
            reviewEntries.add(new Entry(index, review));
            xLabels.add(date.substring(5)); // MM-dd
            index++;
        }
        c.close();

        LineDataSet set1 = new LineDataSet(learnEntries, "学习");
        set1.setColor(0xFF00BCD4);
        set1.setCircleColor(0xFF00BCD4);
        set1.setLineWidth(2f);
        set1.setCircleRadius(4f);

        LineDataSet set2 = new LineDataSet(reviewEntries, "复习");
        set2.setColor(0xFFFF9800);
        set2.setCircleColor(0xFFFF9800);
        set2.setLineWidth(2f);
        set2.setCircleRadius(4f);

        LineData data = new LineData(set1, set2);
        lineChart.setData(data);

        // X轴设置
        XAxis xAxis = lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setGranularity(1f);
        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getAxisLabel(float value, AxisBase axis) {
                int i = (int) value;
                return (i >= 0 && i < xLabels.size()) ? xLabels.get(i) : "";
            }
        });

        // Y轴设置
        YAxis leftAxis = lineChart.getAxisLeft();
        leftAxis.setAxisMinimum(0f);
        lineChart.getAxisRight().setEnabled(false);

        lineChart.getDescription().setEnabled(false);
        lineChart.getLegend().setEnabled(true);
        lineChart.invalidate();
    }

    @Override
    protected void onDestroy() {
        dbHelper.close();
        super.onDestroy();
    }
}